<template>
  <div class="sx-common-form-richtext">
    <div :id="id" :value="value"></div>
  </div>
</template>

<script>
// import $ from "jquery";
import SparkMD5 from "./lib/sparkMd5/sparkMd5.min";
export default {
  name: "SxCommonFormRichtext",
  props: {
    value: {
      type: String,
    },
    id: {
      type: String,
      required: true,
    },
    tinymcePath: {
      type: String,
      default: "/static/tinymce-5.1.1/",
    },
    height: {
      type: Number,
      default: 400,
    },
    plugins: {
      type: String,
      default:
        "lists image table wordcount code link hr preview searchreplace paste",
    },
    toolbar: {
      type: String,
      default:
        "undo redo |  formatselect | bold italic hr forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | code searchreplace link preview | removeformat",
    },
    uploadType: {
      type: String,
      default: "qiniu",
    },
    localApi: {
      type: String,
      default: "/UEditor/FileUp",
    },
    qiniuApi: {
      type: String,
      default: "http://up.qiniu.com",
    },
    qiniuTokenApi: {
      type: String,
      default: "/File/QNToken?md5=",
    },
    uploadImg: {
      type: Function,
      // default: (file, success, fail) => {},
    },
    uploadFiles: {
      type: Function,
      // default: (file, success) => {},
    },
    qiniuApiResFn: {
      type: Function,
      default: (res) => {
        return res;
      },
    },
    qiniuTokenApiResFn: {
      type: Function,
      default: (res) => {
        return res;
      },
    },
    localApiResFn: {
      type: Function,
      default: (res) => {
        return res;
      },
    },
  },
  data() {
    return {
      loading: false, //文件切片是否进行中
    };
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    // 销毁
    window.tinymce.remove(`#${this.id}`);
    // window.tinymce.get(this.editorId).destroy();
  },
  methods: {
    async init() {
      await this.addScriptTag("tinymce.min.js");
      setTimeout(() => {
        this.tinymceInit();
      }, 500);
    },
    async tinymceInit() {
      await window.tinymce.init({
        editor_css: this.tinymcePath + "edit.css",
        content_css: this.tinymcePath + "edit.css",
        selector: `#${this.id}`,
        // language_url: '/assets/tinymce/lang/zh_CN.js', // 语言包的路径
        language: "zh_CN", // 语言
        // skin_url: '/assets/tinymce-5.1.1/skins/ui/oxide', // skin路径，注意这个，很多网上教程都是skins/lightgray，但是发现其实并没有这个玩意儿
        height: this.height, // 编辑器高度
        branding: false, // false隐藏右下角技术支持
        menubar: true, // 顶部菜单栏显示
        plugins: this.plugins,
        toolbar: this.toolbar,
        auto_cleanup_word: true,
        paste_retain_style_properties: "text-indent", //paste 从Word粘贴过来时，允许保留的样式，多个样式属性名用空格分隔
        // 图片上传函数
        images_upload_handler: (blobInfo, succFun, failFun) => {
          let file = blobInfo.blob(); // 转化为易于理解的file对象
          if (this.uploadImg) {
            this.uploadImg(file, succFun, failFun); //父组件重写上传方法
          } else {
            if (this.uploadType == "qiniu") {
              this.uploadQiniu(file)
                .then((res) => {
                  succFun(res.url);
                })
                .catch((e) => {
                  failFun(e);
                });
            } else {
              this.uploadFile(file)
                .then((res) => {
                  succFun(res.url);
                })
                .catch((e) => {
                  failFun(e);
                });
            }
          }
        },
        // 文件上传函数
        file_picker_callback: (callback, value, meta) => {
          let input = document.createElement("input");
          let _this = this;
          input.setAttribute("type", "file");
          input.click();
          input.onchange = function () {
            let file = this.files[0];
            if (_this.uploadFiles) {
              _this.uploadFiles(file, callback);
            } else {
              if (_this.uploadType === "qiniu") {
                _this.uploadQiniu(file).then((res) => {
                  callback(res.url, {
                    text: res.name,
                  });
                });
              } else {
                _this.uploadFile(file).then((res) => {
                  callback(res.url, {
                    text: res.original,
                  });
                });
              }
            }
          };
        },
        //监听
        setup: (editor) => {
          editor.on("init", () => {
            editor.setContent(this.value);
          });
          //值改变监听
          editor.on("change keyup", () => {
            var content = editor.getContent();
            content = content.replace(/font-family:[^;]+;/g, "");
            // 更新文本
            //editor.save();
            this.$emit("input", content);
          });
          editor.on("undo redo", () => {
            var content = editor.getContent();
            content = content.replace(/font-family:[^;]+;/g, "");
            // 更新文本
            this.$emit("input", content);
            // if(this.$parent.form&&this.$parent.form[this.editorId]){
            //   this.$parent.form[this.editorId]=content
            // }
          });
          editor.on("blur", () => {
            this.$emit("blur");
          });
          editor.on("focus", () => {
            this.$emit("focus");
          });
        },
      });
    },
    /**
     * 上传文件/图片到项目服务器
     * @param file 文件
     */
    uploadFile(file) {
      return new Promise((resolve, reject) => {
        let formData = new FormData();
        formData.append("files", file);
        // $.ajax({
        //   url: this.uploadPath, // 请求的接口地址
        //   type: "POST",
        //   cache: false, // 上传文件不需要缓存
        //   data: formData,
        //   processData: false, // 不要去处理发送的数据
        //   contentType: false, // 不要去设置Content-Type请求头
        //   success: (ret) => {
        //     let res = this.localApiResFn(ret);
        //     if (res.state == "SUCCESS") {
        //       resolve(res);
        //     }
        //   },
        //   error: (err) => {
        //     reject(err);
        //   },
        // });
      });
    },
    /**
     * 上传文件到七牛服务器
     * @param file 文件
     */
    uploadQiniu(file) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        let blobSlice =
          File.prototype.slice ||
          File.prototype.mozSlice ||
          File.prototype.webkitSlice;
        let chunkSize = 2097152; //文件切割，以2MB作为一个片段
        let chunkCount = Math.ceil(file.size / chunkSize); //切割总片段
        let currentChunk = 0; //当前片段
        let spark = new SparkMD5.ArrayBuffer();
        let fileReader = new FileReader();
        let that = this;
        //加载下一块
        function loadNext() {
          let start = currentChunk * chunkSize;
          let end = start + chunkSize;
          if (end >= file.size) {
            end = file.size;
          }
          var chunk = blobSlice.call(file, start, end);
          fileReader.readAsArrayBuffer(chunk);
        }
        fileReader.onload = function (e) {
          var result = e.target.result; //二进制流
          spark.append(result); //添加到数组中
          currentChunk = currentChunk + 1; //添加下一块
          //继续添加下一块
          if (currentChunk < chunkCount) {
            loadNext();
          } else {
            //结束
            that.loading = false;
            var md5 = spark.end().toUpperCase(); //生成该文件的md5
            file.md5 = md5;
            // $.ajax({
            //   url: that.qiniuTokenApi + md5,
            //   type: "get",
            //   data: {},
            //   dataType: "json",
            //   success: (ret) => {
            //     let response = that.qiniuTokenApiResFn(ret);
            //     let token = response.uptoken;
            //     //key格式:{guid}/{文件名}.{扩展名}
            //     let guid = Date.now() + that.getFileType(file) + file.size;
            //     let key = guid + "/" + file.name;
            //     // that.signKey = key;
            //     file.key = key;
            //     file.token = token;
            //     let formData = new FormData();
            //     formData.append("file", file);
            //     formData.append("key", key);
            //     formData.append("token", token);
            //     upload(formData);
            //   },
            //   fail: (err) => {
            //     console.error(err);
            //     console.error("获取上传文件令牌失败！请联系客服");
            //   },
            // });
          }
        };
        loadNext();
        function upload(formData) {
          // $.ajax({
          //   url: that.qiniuApi, // 请求的接口地址
          //   type: "POST",
          //   cache: false, // 上传文件不需要缓存
          //   data: formData,
          //   processData: false, // 不要去处理发送的数据
          //   contentType: false, // 不要去设置Content-Type请求头
          //   success: (ret) => {
          //     let res = that.qiniuApiResFn(ret);
          //     resolve(res);
          //   },
          //   error: (err) => {
          //     reject(err);
          //   },
          // });
        }
      });
    },
    getFileType(file) {
      // 获取文件类型
      let name = file.name;
      let index = name.lastIndexOf(".");
      let type = name.substring(index + 1);
      return type;
    },
    addScriptTag(name) {
      return new Promise((resolve, reject) => {
        let scriptTag = document.createElement("script");
        scriptTag.type = "text/javascript";
        scriptTag.src = `${this.tinymcePath}${name}`;
        let head = document.getElementsByTagName("head")[0];
        head.appendChild(scriptTag);
        scriptTag.addEventListener("load", () => {
          console.log("引入tinymce.js成功");
          head.removeChild(scriptTag);
          resolve();
        });
        scriptTag.addEventListener("error", () => {
          console.log("引入tinymce.js异常");
          head.removeChild(scriptTag);
          reject();
        });
      });
    },
  },
};
</script>
<style scoped>
.zhanwei {
  border: 1px solid #cccccc;
  min-height: 1000px;
}
</style>
